package com.newthread.android.ui.bbs;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.text.InputType;
import android.view.*;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.*;
import cn.jpush.im.android.api.JMessageClient;
import cn.jpush.im.android.api.callback.DownloadCompletionCallback;
import cn.jpush.im.android.api.content.EventNotificationContent;
import cn.jpush.im.android.api.content.ImageContent;
import cn.jpush.im.android.api.content.TextContent;
import cn.jpush.im.android.api.content.VoiceContent;
import cn.jpush.im.android.api.event.MessageEvent;
import cn.jpush.im.android.api.model.Conversation;
import cn.jpush.im.android.api.model.Message;
import cn.jpush.im.android.api.model.UserInfo;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.newthread.android.R;
import com.newthread.android.activity.main.MyApplication;
import com.newthread.android.adapter.ChatMsgViewAdapter;
import com.newthread.android.bean.StudentUserLocal;
import com.newthread.android.bean.bbs.ChatMsgEntity;
import com.newthread.android.bean.bbs.SoundMeter;
import com.newthread.android.util.Loger;
import net.tsz.afinal.FinalActivity;
import net.tsz.afinal.FinalDb;
import net.tsz.afinal.annotation.view.ViewInject;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

public class BbsChatActivity extends Activity implements OnClickListener {
    /**
     * Called when the activity is first created.
     */

    @ViewInject(id = R.id.tv_chat_title)
    private TextView chatTitle;
    @ViewInject(id = R.id.btn_send)
    private Button mBtnSend;
    @ViewInject(id = R.id.btn_rcd)
    private TextView mBtnRcd;
    @ViewInject(id = R.id.btn_back)
    private Button mBtnBack;
    @ViewInject(id = R.id.btn_right)
    private ImageButton mBtnRight;
    @ViewInject(id = R.id.et_sendmessage)
    private EditText mEditTextContent;
    @ViewInject(id = R.id.btn_bottom)
    private RelativeLayout mBottom;
    @ViewInject(id = R.id.pull_to_refresh_listView)
    private PullToRefreshListView pullToRefreshListView;
    private ListView mListView;
    @ViewInject(id = R.id.voice_rcd_hint_loading)
    private LinearLayout voice_rcd_hint_loading;
    @ViewInject(id = R.id.voice_rcd_hint_rcding)
    private LinearLayout voice_rcd_hint_rcding;
    @ViewInject(id = R.id.voice_rcd_hint_tooshort)
    private LinearLayout voice_rcd_hint_tooshort;
    @ViewInject(id = R.id.img1)
    private ImageView img1;
    @ViewInject(id = R.id.sc_img1)
    private ImageView sc_img1;
    @ViewInject(id = R.id.rcChat_popup)
    private View rcChat_popup;
    @ViewInject(id = R.id.del_re)
    private LinearLayout del_re;
    @ViewInject(id = R.id.ivPopUp)
    private ImageView chatting_mode_btn;
    @ViewInject(id = R.id.volume)
    private ImageView volume;

    private ChatMsgViewAdapter mAdapter;
    private List<ChatMsgEntity> mDataArrays = new ArrayList<>();
    private boolean isShosrt = false;
    private SoundMeter mSensor;

    private boolean btn_vocie = false;
    private int flag = 1, page = 2;
    private Handler mHandler = new Handler();
    private String voiceName;
    private long startVoiceT, endVoiceT;
    //发送时语音保存路径
    public static final String VOIC_PATH = android.os.Environment.getExternalStorageDirectory() + "/OnMinDa";
    //通过Jpush接收得路径
    public static final String JPUSH_VOIC_PATH = "/data/data/com.newthread.android/files/others/voice";
    //交互的2个用户 暂不考虑群聊天
    private StudentUserLocal toUser, mySelf;

    /**
     * 该类需要的 toUser 可从点击事件得到 或者从 intent过来(必须要有bundle 携带target_id=“学号”)
     *
     * @param savedInstanceState
     */
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_bbs_chat);
        FinalActivity.initInjectedView(this);
        JMessageClient.registerEventReceiver(this);
        FinalDb db = FinalDb.create(getApplicationContext(), "onMinDaBbs");
        //下面if else 是两中进入该界面的方式  一种是从通知栏进来 另一个是点击进来
        //getIntent()内容: "Bundle[{msg_id=57, target_id=2012211884, conv_type=single}]"
        String target_id = getIntent().getStringExtra("target_id");
        try {
            if (target_id != null && target_id.length() > 1) {
                toUser = db.findAllByWhere(StudentUserLocal.class, "studentId=\"" + target_id + "\"").get(0);
            } else {
                //从Application拿到点击用户 这里感觉好像无法用 EventBus
                toUser = MyApplication.getInstance().getThing("clickUser");
            }
            //拿到当前登录极光用户的username即学号
            UserInfo userInfo = JMessageClient.getMyInfo();
            String sql = "studentId=\"" + userInfo.getUserName() + "\"";
            //从数据库中拿到
            mySelf = db.findAllByWhere(StudentUserLocal.class, sql).get(0);
            // 启动activity时不自动弹出软键盘
            getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
            JMessageClient.enterSingleConversaion(toUser.getStudentId());
            initView();
            initData();
        } catch (Exception e) {
            //未先缓存所有用户数据
            Toast.makeText(getApplicationContext(), "请在民大交流中刷新联系人", Toast.LENGTH_LONG).show();
            finish();
            return;
        }
    }

    //销毁时取消注册的EventBus
    @Override
    protected void onDestroy() {
        JMessageClient.unRegisterEventReceiver(this);
        super.onDestroy();
    }

    public void initView() {
        chatTitle.setText(toUser.getName());
        mBtnSend.setOnClickListener(this);
        mBtnBack.setOnClickListener(this);
        mBtnRight.setOnClickListener(this);
        mEditTextContent.setOnClickListener(this);
        //设置EditText的显示方式为多行文本输入
        mEditTextContent.setInputType(InputType.TYPE_TEXT_FLAG_MULTI_LINE);
        //文本显示的位置在EditText的最上方
        mEditTextContent.setGravity(Gravity.TOP);
        //改变默认的单行模式
        mEditTextContent.setSingleLine(false);
        //水平滚动设置为False
        mEditTextContent.setHorizontallyScrolling(false);
        mSensor = new SoundMeter();
        //语音文字切换按钮
        mListView = pullToRefreshListView.getRefreshableView();
        chatting_mode_btn.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                if (btn_vocie) {
                    mBtnRcd.setVisibility(View.GONE);
                    mBottom.setVisibility(View.VISIBLE);
                    btn_vocie = false;
                    chatting_mode_btn.setImageResource(R.drawable.chatting_setmode_msg_btn);
                } else {
                    mBtnRcd.setVisibility(View.VISIBLE);
                    mBottom.setVisibility(View.GONE);
                    chatting_mode_btn.setImageResource(R.drawable.chatting_setmode_voice_btn);
                    btn_vocie = true;
                }
            }
        });
        mBtnRcd.setOnTouchListener(new OnTouchListener() {

            public boolean onTouch(View v, MotionEvent event) {
                //按下语音录制按钮时返回false执行父类OnTouch
                return false;
            }
        });
        pullToRefreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(final PullToRefreshBase<ListView> refreshView) {
                List<Message> messages = getHistroy(page, toUser.getStudentId());
                mDataArrays.addAll(0, changeMsgToChatMsg(messages));
                mAdapter.notifyDataSetChanged();
                if (refreshView != null) {
                    //由于从数据库拿数据太快了 所以要延迟200ms停止刷新，否则刷新不会消失
                    mHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            refreshView.onRefreshComplete();
                        }
                    }, 200);
                }
                page++;
            }
        });
    }

    /**
     * 从本地数据库拿数据来显示页面
     */
    public void initData() {
        List<Message> messages = getHistroy(1, toUser.getStudentId());
        mDataArrays.addAll(changeMsgToChatMsg(messages));
        mAdapter = new ChatMsgViewAdapter(this, mDataArrays);
        mListView.setAdapter(mAdapter);
    }

    /**
     * 将Jpush储存的消息记录转换成 可以适配的自定义的ChatMsg
     *
     * @param messages Jpush的Message 目前只实现 TextMessage 和 VoiceMessage的转换
     * @return 转换好的 list ChatMsgEntity
     */
    private List<ChatMsgEntity> changeMsgToChatMsg(List<Message> messages) {
        List<ChatMsgEntity> list = new ArrayList<>();
        for (Message msg : messages) {
            switch (msg.getContentType()) {
                case text:
                    ChatMsgEntity entity = new ChatMsgEntity();
                    String studentID = msg.getFromID();
                    TextContent textContent = (TextContent) msg.getContent();
                    if (studentID.equals(mySelf.getStudentId())) {
                        entity.setHeadPhoto(mySelf.getHeadPhotoUrl());
                        entity.setName(mySelf.getName());
                        entity.setMsgType(false);
                    } else {
                        entity.setHeadPhoto(toUser.getHeadPhotoUrl());
                        entity.setName(toUser.getName());
                        entity.setMsgType(true);
                    }
                    entity.setDate(parseDate(msg.getCreateTime()));
                    entity.setText(textContent.getText());
                    list.add(entity);
                    break;
                case voice:
                    ChatMsgEntity entity1 = new ChatMsgEntity();
                    String studentID1 = msg.getFromID();
                    VoiceContent voiceContent = (VoiceContent) msg.getContent();
                    if (studentID1.equals(mySelf.getStudentId())) {
                        entity1.setHeadPhoto(mySelf.getHeadPhotoUrl());
                        entity1.setName(mySelf.getName());
                        entity1.setMsgType(false);
                    } else {
                        entity1.setHeadPhoto(toUser.getHeadPhotoUrl());
                        entity1.setName(toUser.getName());
                        entity1.setMsgType(true);
                    }
                    entity1.setDate(parseDate(msg.getCreateTime()));
                    entity1.setTime(voiceContent.getDuration() + "\"");
                    String tempVoiceName = voiceContent.getMediaID().substring(12);
                    File mFile = new File(JPUSH_VOIC_PATH + "/" + tempVoiceName + ".amr");
                    checkVoice(mFile, msg);
                    entity1.setText(mFile.getAbsolutePath());
                    list.add(entity1);
                    break;
                default:
            }

        }
        return list;
    }

    private void checkVoice(final File mFile, Message msg) {
        if (mFile.exists()) {
            return;
        }
        ((VoiceContent) msg.getContent()).downloadVoiceFile(msg, new DownloadCompletionCallback() {
            @Override
            public void onComplete(int i, String s, File file) {
                file.renameTo(mFile);
            }
        });
    }


    /**
     * 按倒序方式 分页查询 Jpush储存的聊天信息 然后逆序转换
     *
     * @param page     第几页
     * @param username clickUser 的studentId
     * @return
     */
    private List<Message> getHistroy(int page, String username) {
        List<Message> list = new ArrayList<>();
        int index = page * 15;
        Conversation conversation = JMessageClient.getSingleConversation(username);
        if (conversation != null) {
            List<Message> temp = conversation.getMessagesFromNewest(index - 15, index);
            int len = temp.size();
            for (int i = 0; i < len; i++) {
                list.add(temp.get(len - i - 1));
            }
        }
        return list;
    }

    /**
     * 发送文字
     *
     * @param toUser   发送过去的 user
     * @param fromUser 发送着
     */
    private void sendText(StudentUserLocal toUser, StudentUserLocal fromUser) {
        String contString = mEditTextContent.getText().toString();
        if (contString.length() > 0) {
            ChatMsgEntity entity = new ChatMsgEntity();
            entity.setHeadPhoto(fromUser.getHeadPhotoUrl());
            entity.setDate(getDate());
            entity.setName(fromUser.getName());
            entity.setMsgType(false);
            entity.setText(contString);
            mDataArrays.add(entity);
            mAdapter.notifyDataSetChanged();
            mEditTextContent.setText("");
            changeListView(50);
            //Jpush推送消息 注意不能一台手机给自己发送 我搞了几个小时妈的
            Message msg = JMessageClient.createSingleTextMessage(toUser.getStudentId(), contString);
            JMessageClient.sendMessage(msg);
        }
    }

    /**
     * 发送语音
     *
     * @param time
     */
    private void sendVoice(final int time, final StudentUserLocal toUser, StudentUserLocal fromUser) {
        ChatMsgEntity entity = new ChatMsgEntity();
        entity.setHeadPhoto(fromUser.getHeadPhotoUrl());
        entity.setDate(getDate());
        entity.setName(fromUser.getName());
        entity.setMsgType(false);
        entity.setTime(time + "\"");
        entity.setText(voiceName);
        mDataArrays.add(entity);
        mAdapter.notifyDataSetChanged();
        changeListView(50);
        //Jpush推送消息声音
        try {
            Message msg = JMessageClient.createSingleVoiceMessage(toUser.getStudentId(), new File(VOIC_PATH + "/" + voiceName), time);
            JMessageClient.sendMessage(msg);
        } catch (FileNotFoundException e) {
            Toast.makeText(getApplicationContext(), "保存音频文件失败，请检查储存卡情况。", Toast.LENGTH_LONG).show();
        }
    }

    /**
     * 得到文字信息后调用
     *
     * @param fromUser
     * @param contString
     */
    private void getText(StudentUserLocal fromUser, String contString) {
        ChatMsgEntity entity = new ChatMsgEntity();
        entity.setHeadPhoto(fromUser.getHeadPhotoUrl());
        entity.setDate(getDate());
        entity.setName(fromUser.getName());
        entity.setMsgType(true);
        entity.setText(contString);
        mDataArrays.add(entity);
        mAdapter.notifyDataSetChanged();
        changeListView(50);
    }

    /**
     * 得到语音信息后调用
     *
     * @param fromUser
     * @param getVoicePaht
     */
    private void getVoice(StudentUserLocal fromUser, String getVoicePaht) {
        ChatMsgEntity entity = new ChatMsgEntity();
        entity.setHeadPhoto(fromUser.getHeadPhotoUrl());
        entity.setDate(getDate());
        entity.setName(fromUser.getName());
        entity.setMsgType(true);
        entity.setText(getVoicePaht);
        mDataArrays.add(entity);
        mAdapter.notifyDataSetChanged();
        changeListView(50);
    }

    /**
     * Jpush推送成功后显示接口 用于实时聊天(基于EventBus实现，不知道可以看git提交日志的网站,一看你就明白了)
     *
     * @param event
     */
    public void onEventMainThread(MessageEvent event) {
        Message msg = event.getMessage();
        //如果接受的信息不是当前点击用户，跳出该方法
        if (!msg.getFromID().equals(toUser.getStudentId()))
            return;
        switch (msg.getContentType()) {
            case text:
                //处理文字消息
                TextContent textContent = (TextContent) msg.getContent();
                getText(toUser, textContent.getText());
                break;
            case image:
                ImageContent imageContent = (ImageContent) msg.getContent();
                //处理图片消息
                break;
            case voice:
                VoiceContent voiceContent = (VoiceContent) msg.getContent();
                //处理语音消息
                voiceContent.downloadVoiceFile(msg, new DownloadCompletionCallback() {
                    @Override
                    public void onComplete(int i, String s, File file) {
                        final String path = file.getAbsolutePath();
                        if (file.renameTo(new File(path + ".amr"))) {
                            getVoice(toUser, path + ".amr");
                        }
                    }
                });
                break;
            case custom:
                //处理自定义消息
                break;
            case eventNotification:
                //处理事件提醒消息
                EventNotificationContent eventNotificationContent = (EventNotificationContent) msg.getContent();
                switch (eventNotificationContent.getEventNotificationType()) {
                    case group_member_added:
                        //群成员加群事件
                        break;
                    case group_member_removed:
                        //群成员被踢事件
                        break;
                    case group_member_exit:
                        //群成员退群事件
                        break;
                }
                break;
        }

    }

    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_send:
                //点击发送 发送信息到 toUser
                sendText(toUser, mySelf);
                break;
            case R.id.btn_back:
                finish();
                break;
            case R.id.et_sendmessage:
                //要等软键盘弹出后 设置listView位置 设置0.3秒
                changeListView(300);
                break;
            case R.id.btn_right:
                //TODO 显示toUser详细信息
//                MyApplication.getInstance().putThing("toUser",toUser);
//                Intent intent = new Intent(getApplicationContext(),BbsUserInfoActivity.class);
//                startActivity(intent);
                break;
        }
    }

    private void changeListView(int dealyTime) {
        mHandler.postDelayed(new Runnable() {
            public void run() {
                mListView.setSelection(mListView.getCount() - 1);
            }
        }, dealyTime);
    }

    /**
     * 得到当前时间 并且按Qq的方式显示
     *
     * @return
     */
    private String getDate() {
        Calendar c = Calendar.getInstance();
        String year = String.valueOf(c.get(Calendar.YEAR));
        String month = String.valueOf(c.get(Calendar.MONTH));
        String day = String.valueOf(c.get(Calendar.DAY_OF_MONTH) + 1);
        String hour = String.valueOf(c.get(Calendar.HOUR_OF_DAY));
        String mins = String.valueOf(c.get(Calendar.MINUTE));
        StringBuffer sbBuffer = new StringBuffer();
        sbBuffer.append(year + "-" + month + "-" + day + " " + hour + ":" + mins);
        return sbBuffer.toString();
    }

    /**
     * 将数据库long时间类型转换成 QQ显示时间的类型 和上面一样
     *
     * @param l
     * @return
     */
    private String parseDate(long l) {
        Calendar c = Calendar.getInstance();
        c.setTimeInMillis(l);
        String year = String.valueOf(c.get(Calendar.YEAR));
        String month = String.valueOf(c.get(Calendar.MONTH));
        String day = String.valueOf(c.get(Calendar.DAY_OF_MONTH) + 1);
        String hour = String.valueOf(c.get(Calendar.HOUR_OF_DAY));
        String mins = String.valueOf(c.get(Calendar.MINUTE));
        StringBuffer sbBuffer = new StringBuffer();
        sbBuffer.append(year + "-" + month + "-" + day + " " + hour + ":" + mins);
        return sbBuffer.toString();
    }

    //按下语音录制按钮时
    @Override
    public boolean onTouchEvent(MotionEvent event) {

        if (!Environment.getExternalStorageDirectory().exists()) {
            Toast.makeText(this, "No SDCard", Toast.LENGTH_LONG).show();
            return false;
        }

        if (btn_vocie) {
            Loger.V("捕获录音onTouch事件");
            int[] location = new int[2];
            mBtnRcd.getLocationInWindow(location); // 获取在当前窗口内的绝对坐标
            int btn_rc_Y = location[1];
            int btn_rc_X = location[0];
            int[] del_location = new int[2];
            del_re.getLocationInWindow(del_location);
            int del_Y = del_location[1];
            int del_x = del_location[0];
            if (event.getAction() == MotionEvent.ACTION_DOWN && flag == 1) {
                if (!Environment.getExternalStorageDirectory().exists()) {
                    Toast.makeText(this, "No SDCard", Toast.LENGTH_LONG).show();
                    return false;
                }
                Loger.V("按下事件");
                if (event.getY() > btn_rc_Y && event.getX() > btn_rc_X) {//判断手势按下的位置是否是语音录制按钮的范围内
                    Loger.V("按下事件在录制按钮内");
                    mBtnRcd.setBackgroundResource(R.drawable.voice_rcd_btn_pressed);
                    rcChat_popup.setVisibility(View.VISIBLE);
                    voice_rcd_hint_loading.setVisibility(View.VISIBLE);
                    voice_rcd_hint_rcding.setVisibility(View.GONE);
                    voice_rcd_hint_tooshort.setVisibility(View.GONE);
                    mHandler.postDelayed(new Runnable() {
                        public void run() {
                            if (!isShosrt) {
                                voice_rcd_hint_loading.setVisibility(View.GONE);
                                voice_rcd_hint_rcding
                                        .setVisibility(View.VISIBLE);
                            }
                        }
                    }, 300);
                    img1.setVisibility(View.VISIBLE);
                    del_re.setVisibility(View.GONE);
                    startVoiceT = System.currentTimeMillis();
                    voiceName = startVoiceT + ".amr";
                    start(voiceName);
                    flag = 2;
                }
            } else if (event.getAction() == MotionEvent.ACTION_UP && flag == 2) {//松开手势时执行录制完成
                Loger.V("松开事件");
                mBtnRcd.setBackgroundResource(R.drawable.voice_rcd_btn_nor);
                if (event.getY() >= del_Y
                        && event.getY() <= del_Y + del_re.getHeight()
                        && event.getX() >= del_x
                        && event.getX() <= del_x + del_re.getWidth()) {
                    //松开手指时 位于取消录音按钮上 则删除音频
                    rcChat_popup.setVisibility(View.GONE);
                    img1.setVisibility(View.VISIBLE);
                    del_re.setVisibility(View.GONE);
                    stop();
                    flag = 1;
                    File file = new File(VOIC_PATH + "/" + voiceName);
                    if (file.exists()) {
                        file.delete();
                        Loger.V("手动取消录音 删除文件" + file.getAbsolutePath());
                    }
                } else {
                    voice_rcd_hint_rcding.setVisibility(View.GONE);
                    endVoiceT = System.currentTimeMillis();
                    int time = (int) (endVoiceT - startVoiceT) / 1000;
                    if (time == 0) {
                        //时间为0直接执行此方法会崩溃 延迟500ms删除文件
                        mHandler.postDelayed(new Runnable() {
                            public void run() {
                                stop();
                                File file = new File(VOIC_PATH + "/" + voiceName);
                                if (file.exists()) {
                                    file.delete();
                                    Loger.V("录音时间太短 延迟500ms然后删除文件" + file.getAbsolutePath());
                                }
                            }
                        }, 500);
                    } else {
                        //时间为0直接执行此方法会崩溃
                        stop();
                    }
                    flag = 1;
                    //time==0执行下面if 方法显示十时间太短
                    if (time < 1) {
                        isShosrt = true;
                        voice_rcd_hint_loading.setVisibility(View.GONE);
                        voice_rcd_hint_rcding.setVisibility(View.GONE);
                        voice_rcd_hint_tooshort.setVisibility(View.VISIBLE);
                        mHandler.postDelayed(new Runnable() {
                            public void run() {
                                voice_rcd_hint_tooshort.setVisibility(View.GONE);
                                rcChat_popup.setVisibility(View.GONE);
                                isShosrt = false;
                            }
                        }, 500);
                        return false;
                    }
                    sendVoice(time, toUser, mySelf);
                    rcChat_popup.setVisibility(View.GONE);

                }
            }
            if (event.getY() < btn_rc_Y) {//手势按下的位置不在语音录制按钮的范围内
                System.out.println("5");
                Animation mLitteAnimation = AnimationUtils.loadAnimation(this,
                        R.anim.cancel_rc);
                Animation mBigAnimation = AnimationUtils.loadAnimation(this,
                        R.anim.cancel_rc2);
                img1.setVisibility(View.GONE);
                del_re.setVisibility(View.VISIBLE);
                del_re.setBackgroundResource(R.drawable.voice_rcd_cancel_bg);
                if (event.getY() >= del_Y
                        && event.getY() <= del_Y + del_re.getHeight()
                        && event.getX() >= del_x
                        && event.getX() <= del_x + del_re.getWidth()) {
                    del_re.setBackgroundResource(R.drawable.voice_rcd_cancel_bg_focused);
                    sc_img1.startAnimation(mLitteAnimation);
                    sc_img1.startAnimation(mBigAnimation);
                }
            } else {

                img1.setVisibility(View.VISIBLE);
                del_re.setVisibility(View.GONE);
                del_re.setBackgroundResource(0);
            }
        }
        return super.onTouchEvent(event);
    }

    private static final int POLL_INTERVAL = 300;
    private Runnable mSleepTask = new Runnable() {
        public void run() {
            stop();
        }
    };
    private Runnable mPollTask = new Runnable() {
        public void run() {
            double amp = mSensor.getAmplitude();
            updateDisplay(amp);
            mHandler.postDelayed(mPollTask, POLL_INTERVAL);
        }
    };

    /**
     * 录制音频
     *
     * @param name
     */
    private void start(String name) {
        mSensor.start(name);
        mHandler.postDelayed(mPollTask, POLL_INTERVAL);
    }

    /**
     * 停止录制
     */
    private void stop() {
        mHandler.removeCallbacks(mSleepTask);
        mHandler.removeCallbacks(mPollTask);
        mSensor.stop();
        volume.setImageResource(R.drawable.amp1);
    }

    /**
     * 显示录制动画
     *
     * @param signalEMA
     */
    private void updateDisplay(double signalEMA) {

        switch ((int) signalEMA) {
            case 0:
            case 1:
                volume.setImageResource(R.drawable.amp1);
                break;
            case 2:
            case 3:
                volume.setImageResource(R.drawable.amp2);

                break;
            case 4:
            case 5:
                volume.setImageResource(R.drawable.amp3);
                break;
            case 6:
            case 7:
                volume.setImageResource(R.drawable.amp4);
                break;
            case 8:
            case 9:
                volume.setImageResource(R.drawable.amp5);
                break;
            case 10:
            case 11:
                volume.setImageResource(R.drawable.amp6);
                break;
            default:
                volume.setImageResource(R.drawable.amp7);
                break;
        }
    }
}